package com.ruike.alisurface.services;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.SignalStrength;
import android.telephony.TelephonyManager;

import com.ruike.alisurface.utils.ShareKey;
import com.ruike.alisurface.utils.ThreadUtils;
import com.ruike.alisurface.utils.TimeUtils;
import com.voodoo.lib_utils.L;
import com.voodoo.lib_utils.ShareUtils;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Author: voodoo
 * CreateDate: 2020/02/19 019 下午 03:08:04
 * Description: 网络监听的服务
 */
public class NetWorkListenerService extends Service {

    public TelephonyManager mTelephonyManager;
    public PhoneStatListener mListener;
    private NetWorkBroadCastReciver mNetWorkBroadCastReciver;
    public int mGsmSignalStrength;
    public int checkNumber = 0;

    @Override
    public void onCreate() {
        super.onCreate();
        L.i("mqtt  开启信号检测服务");
        // 开始监听
        mListener = new PhoneStatListener();
        // 获取telephonyManager
        mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        // 由于信号值变化不大时，监听反应不灵敏，所以通过广播的方式同时监听wifi和信号改变更灵敏
        mNetWorkBroadCastReciver = new NetWorkBroadCastReciver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        intentFilter.addAction(WifiManager.RSSI_CHANGED_ACTION);
        registerReceiver(mNetWorkBroadCastReciver, intentFilter);

        // 服务被创建的时候开始监听
        mTelephonyManager.listen(mListener, PhoneStatListener.LISTEN_SIGNAL_STRENGTHS);
        //主动去查询当前网络信号
        Timer getNetWorkInfoTimer = new Timer();
        TimerTask getNetWorkInfoTimerTask = new TimerTask() {
            @Override
            public void run() {
                checkNumber++;
                if (checkNumber >= 20) {
                    checkNumber = 0;
//                    L.i("mqtt 重置机器重启次数 时间比对"+TimeUtils.millis2String(System.currentTimeMillis(),"HH:mm"));
                    if (TimeUtils.millis2String(System.currentTimeMillis(), "HH:mm").equals("00:00")) {
                        L.i("mqtt 重置机器重启次数");
                        ShareUtils.getInstance().putInt(ShareKey.IS_OFFLINE_RESTART_APPCOUNT, 10);
                    }
                }
                ThreadUtils.postUI(new Runnable() {
                    @Override
                    public void run() {
                        getNetWorkInfo();
                    }
                });
            }
        };
        getNetWorkInfoTimer.schedule(getNetWorkInfoTimerTask, 0, 3_000);
    }

    /**
     * 网络信号的变化监听
     */
    private class PhoneStatListener extends PhoneStateListener {
        @Override
        public void onSignalStrengthsChanged(SignalStrength signalStrength) {
            super.onSignalStrengthsChanged(signalStrength);
            // 获取网络信号强度
            // 获取0-4的5种信号级别，越大信号越好,但是api23开始才能用
            mGsmSignalStrength = signalStrength.getGsmSignalStrength();
            L.i("当前信号强度改变：" + mGsmSignalStrength);
            // 网络信号改变时，获取网络信息
            getNetWorkInfo();
        }
    }


    /**
     * 接收网络状态改变的广播
     */
    class NetWorkBroadCastReciver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            getNetWorkInfo();
        }
    }

    public static PhoneWaftListener mPhoneWaftListener;

    public static void setPhoneWaftListener(PhoneWaftListener phoneWaftListener) {
        mPhoneWaftListener = phoneWaftListener;
    }

    public interface PhoneWaftListener {
        void onStrengthsChanged(String type, int signalStrength);

    }

    /**
     * 获取网络的信息
     */
    private void getNetWorkInfo() {
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = connectivityManager.getActiveNetworkInfo();
        if (info != null && info.isAvailable()) {
            switch (info.getType()) {
                case ConnectivityManager.TYPE_WIFI: // WIFI
                    checkWifiState();
                    break;
                case ConnectivityManager.TYPE_MOBILE: // 移动网络,可以通过TelephonyManager来获取具体细化的网络类型
                    if (mPhoneWaftListener != null) {
                        mPhoneWaftListener.onStrengthsChanged("TYPE_MOBILE", mGsmSignalStrength);
                    }
                    break;
            }
        } else {
            if (mPhoneWaftListener != null) {
                mPhoneWaftListener.onStrengthsChanged("TYPE_MOBILE", 0);
            }
        }
    }

    /**
     * 检查wifi是否处开连接状态
     *
     * @return
     */
    public boolean isWifiConnect() {
        ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mWifiInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        return mWifiInfo.isConnected();
    }

    /**
     * 检查wifi强弱并更改图标显示
     */
    public void checkWifiState() {
        if (isWifiConnect()) {
            @SuppressLint("WifiManagerLeak") WifiManager mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
            WifiInfo mWifiInfo = mWifiManager.getConnectionInfo();
            int wifi = mWifiInfo.getRssi();//获取wifi信号强度
            if (mPhoneWaftListener != null) {
                mPhoneWaftListener.onStrengthsChanged("TYPE_WIFI", wifi);
            }
        } else {
            //无连接
            if (mPhoneWaftListener != null) {
                mPhoneWaftListener.onStrengthsChanged("TYPE_WIFI", -100);
            }
        }
    }

    /**
     * 判断网络速度
     */
    private boolean isFastMobileNetwork() {
        // 这里只简单区分两种类型网络，认为4G网络为快速，但最终还需要参考信号值
        return mTelephonyManager.getNetworkType() == TelephonyManager.NETWORK_TYPE_LTE;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // 服务被销毁的时候，停止监听并解绑广播接收器
        mTelephonyManager.listen(mListener, PhoneStatListener.LISTEN_NONE);
        unregisterReceiver(mNetWorkBroadCastReciver);
    }
}
